package net.code;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class Decoder extends CumulativeProtocolDecoder {
	public static final int MAX_MSG_SIZE = 4096;

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		try {
			if (in.prefixedDataAvailable(4, MAX_MSG_SIZE)) {
				int length = in.getInt();
				byte[] bytes = new byte[length];
				in.get(bytes);
				out.write(bytes);
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			// TODO: handle exception
//			e.printStackTrace();
			return false;
		}
	}

}
